package com.lashou.chunshen.lashoutuangou.fragments;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lashou.chunshen.lashoutuangou.R;
import com.lashou.chunshen.lashoutuangou.adapter.FenleiPageAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.GalleryAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.HomeBannerAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.HomeViewpagerbannerAdapter;
import com.lashou.chunshen.lashoutuangou.adapter.TopLinePageAdapter;
import com.lashou.chunshen.lashoutuangou.bean.BaseBean;
import com.lashou.chunshen.lashoutuangou.bean.HomeBanner;
import com.lashou.chunshen.lashoutuangou.bean.HomeCategory;
import com.lashou.chunshen.lashoutuangou.bean.HotFilm;
import com.lashou.chunshen.lashoutuangou.core.BaseFragment;
import com.lashou.chunshen.lashoutuangou.nohttp.CallServer;
import com.lashou.chunshen.lashoutuangou.nohttp.HttpListner;
import com.lashou.chunshen.lashoutuangou.nohttp.helper.BeanJsonRequest;
import com.lashou.chunshen.lashoutuangou.tools.AppApplication;
import com.lashou.chunshen.lashoutuangou.tools.ConstantPool;
import com.lashou.chunshen.lashoutuangou.tools.L;
import com.lashou.chunshen.lashoutuangou.tools.ToastUtil;
import com.lashou.chunshen.lashoutuangou.widget.banner.Banner;
import com.lashou.chunshen.lashoutuangou.widget.banner.BannerPagerAdapter;
import com.lashou.chunshen.lashoutuangou.widget.verticalviewpager.VerticalViewPager;
import com.lashou.chunshen.lashoutuangou.widget.verticalviewpager.transformer.DefaultTransformer;
import com.nineoldandroids.view.ViewHelper;
import com.yolanda.nohttp.rest.Response;

import butterknife.InjectView;

/**
 * Created by Administrator on 2016/9/2.
 */

public class HomeFragment01 extends BaseFragment implements AbsListView.OnScrollListener {
    @InjectView(R.id.psv_to_refresh)
    PullToRefreshListView pullToRefreshListView; //总框架
    @InjectView(R.id.top_bar)
    RelativeLayout titleBar; //titlebar
    Banner banner;
    ViewPager fenleiViewPager;
    ViewPager banner_vp;
    LinearLayout pointLayout;
    VerticalViewPager topLine;
    private ViewGroup vg;//放置圆点
    private ViewGroup headbanner_vg;//放置headbanner圆点
    //实例化原点View
    private ImageView iv_point;
    private ImageView[] ivPointArray;
    private ImageView[] ivPointArray_headbanner;
    private int[] imageIdArray;//图片资源的数组

    RecyclerView hotfile_recycleView; //热门电影
    int gdNum; //计算分类的总页数
    private int mFirstItem = 0;
    private int defaultHeight = 0;
    private SparseArray<ItemRecod> RecodSA = new SparseArray<>();

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        View headerView = View.inflate(getActivity(), R.layout.fragment_home_main01, null);
        headerView.setLayoutParams(layoutParams);
        banner = (Banner) headerView.findViewById(R.id.banner);
        fenleiViewPager = (ViewPager) headerView.findViewById(R.id.guide_vp);
        banner_vp = (ViewPager) headerView.findViewById(R.id.banner_vp);
        vg = (ViewGroup) headerView.findViewById(R.id.guide_ll_point);
        headbanner_vg = (ViewGroup) headerView.findViewById(R.id.banner_ll_point);
        pointLayout = (LinearLayout) headerView.findViewById(R.id.iv_image);
        //TopLine
        topLine = (VerticalViewPager) headerView.findViewById(R.id.vp_headlines);
        hotfile_recycleView = (RecyclerView) headerView.findViewById(R.id.id_recyclerview_horizontal);//热门电影
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getHoldingActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        hotfile_recycleView.setLayoutManager(linearLayoutManager);
        pullToRefreshListView.getRefreshableView().addHeaderView(headerView);
        pullToRefreshListView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strs));
        pullToRefreshListView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, strs));
        pullToRefreshListView.setOnScrollListener(this);
        //滑动titlebar变色
        pullToRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mFirstItem = firstVisibleItem;
                // 当前页的第一个Item的View对象
                View firstView = view.getChildAt(0);
                if (null != firstView) {
                    ItemRecod itemRecord = RecodSA.get(firstVisibleItem);
                    if (null == itemRecord) {//处理快速滑动时，跳过的情况
                        //检测有没有跳过
                        for (int i = 0; i < firstVisibleItem; i++) {
                            if (null == RecodSA.get(i)) {//被跳过了，取上一个的高度，top不用管
                                ItemRecod skipItem = new ItemRecod();
                                skipItem.height = defaultHeight;
                                RecodSA.append(i, skipItem);
                            }
                        }
                        itemRecord = new ItemRecod();
                    }
                    itemRecord.height = defaultHeight = firstView.getHeight();
                    itemRecord.top = firstView.getTop();
                    RecodSA.append(firstVisibleItem, itemRecord);
                }
                float alpha = ((float) (getScrollY()) / (float) (500));
                if (alpha > 1.0f) {
                    alpha = 1.0f;
                }
                ViewHelper.setAlpha(titleBar, alpha);
            }

            private int getScrollY() {
                int height = 0;
// 此处采用循环遍历的方式而不用height*item数量的原因是，item的高度可能不一致。
                for (int i = 0; i < mFirstItem; i++) {
                    ItemRecod itemRecod = RecodSA.get(i);
//处理快速滑动
                    height += itemRecod.height;
                }
                ItemRecod itemRecod = RecodSA.get(mFirstItem);
                if (null == itemRecod) {
                    itemRecod = new ItemRecod();
                }
                return height - itemRecod.top;
            }

        });
        initData(); //创建所有接口数据
    }

    class ItemRecod {
        int height;
        int top;
    }

    /**
     * 创建分类圆点标签
     **/
    private ImageView[] initPoint(int size, ViewGroup vg, ImageView[] ivPointArray) {
        //根据ViewPager的item数量实例化数组
        ivPointArray = new ImageView[size];
        //循环新建底部圆点ImageView，将生成的ImageView保存到数组中
        for (int i = 0; i < size; i++) {
            iv_point = new ImageView(getHoldingActivity());
            iv_point.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
            iv_point.setPadding(40, 0, 40, 0);//left,top,right,bottom
            ivPointArray[i] = iv_point;
            //第一个页面需要设置为选中状态，这里采用两张不同的图片
            if (i == 0) {
                iv_point.setBackgroundResource(R.drawable.banner_red_radius);
            } else {
                iv_point.setBackgroundResource(R.drawable.banner_white_radius);
            }
            //将数组中的ImageView加入到ViewGroup
            vg.addView(ivPointArray[i]);
        }
        return ivPointArray;
    }

    private void initData() {
        //banner
        BeanJsonRequest<HomeBanner> bannerBeanJsonRequest = new BeanJsonRequest<HomeBanner>(ConstantPool.BANNER, HomeBanner.class);
        CallServer.getInstance().add(getActivity(), 0, bannerBeanJsonRequest, httpListner, false, true);
        //首页分类
        BeanJsonRequest<HomeCategory> homeCategoryJsonRequest = new BeanJsonRequest<HomeCategory>(ConstantPool.HOMECATEGORY, HomeCategory.class);
        CallServer.getInstance().add(getActivity(), 1, homeCategoryJsonRequest, httpListner, false, true);
        //热门电影
        BeanJsonRequest<HotFilm> hotfilmJsonRequest = new BeanJsonRequest<HotFilm>(ConstantPool.HOTFILM, HotFilm.class);
        CallServer.getInstance().add(getActivity(), 2, hotfilmJsonRequest, httpListner, false, true);


    }

    /**
     * 获取网络数据
     **/
    HttpListner httpListner = new HttpListner<BaseBean>() {
        @Override
        public void onSucceed(int what, Response<BaseBean> response) {
            switch (what) {
                case 0:
                    HomeBanner baseBean = (HomeBanner) response.get();
                    initBanner(baseBean);
                    initBanner01(baseBean);
                    initTopLine(baseBean);//创建拉手头条
                    break;
                case 1:
                    HomeCategory homecategory = (HomeCategory) response.get();
                    initHomeCategory01(homecategory);
                    break;
                case 2:
                    HotFilm hotFile = (HotFilm) response.get();
                    initHotFilm(hotFile);
                    break;
            }

        }

        @Override
        public void onFailed(int what, Response<BaseBean> response) {

        }
    };

    /**
     * 创建热门电影
     **/
    private void initHotFilm(HotFilm hotFile) {

        //设置适配器
        GalleryAdapter mAdapter = new GalleryAdapter(getHoldingActivity(), hotFile);
        hotfile_recycleView.setAdapter(mAdapter);
    }

    /**
     * 创建拉手头条
     **/
    private void initTopLine(HomeBanner homeBanner) {
        TopLinePageAdapter toplinepageadapter = new TopLinePageAdapter<HomeBanner>(getHoldingActivity(), homeBanner);
        toplinepageadapter.setViewpager(topLine);
        toplinepageadapter.openAutoLoop();
        toplinepageadapter.setOnClick(new TopLinePageAdapter.OnClick() {
            @Override
            public void onClick(View view, BaseBean bean) {
                ToastUtil.show(getHoldingActivity(), "点击￥￥￥");
            }
        });
        topLine.setAdapter(toplinepageadapter);
        topLine.setPageTransformer(false, new DefaultTransformer());
        //修改添加设置ViewPager的当前页，为了保证上下轮播
        topLine.setCurrentItem(5000000);

    }

    /**
     * 首页分类
     **/
    private void initHomeCategory01(HomeCategory homecategory) {

        final int size = (int) Math.ceil(homecategory.getResults().size() * 1.0 / 8);
        FenleiPageAdapter fenleipageadapter = new FenleiPageAdapter(getHoldingActivity(), homecategory.getResults());
        fenleiViewPager.setAdapter(fenleipageadapter);
        //修改添加设置ViewPager的当前页，为了保证左右轮播
        fenleiViewPager.setCurrentItem(5000000);
        //加载底部圆点
        ivPointArray = initPoint(size, vg, ivPointArray);
        fenleiViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            /**
             * 滑动后的监听
             * @param position
             */
            @Override
            public void onPageSelected(int position) {
                //修改全部的position长度
                int newPosition = position % size;
                //循环设置当前页的标记图
                for (int i = 0; i < size; i++) {
                    ivPointArray[newPosition].setBackgroundResource(R.drawable.banner_red_radius);
                    if (newPosition != i) {
                        ivPointArray[i].setBackgroundResource(R.drawable.banner_white_radius);
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 创建banner01
     **/
    private void initBanner01(HomeBanner homeBanner) {
        final int size = ((HomeBanner) homeBanner).getResults().getHeader_banner().size();
        HomeViewpagerbannerAdapter homeviewpagerbanneradapter = new HomeViewpagerbannerAdapter(getHoldingActivity(), homeBanner);
        homeviewpagerbanneradapter.setViewpager(banner_vp);
        homeviewpagerbanneradapter.openAutoLoop();
        banner_vp.setAdapter(homeviewpagerbanneradapter);
        //修改添加设置ViewPager的当前页，为了保证上下轮播
        banner_vp.setCurrentItem(size * 30);
        //加载底部圆点
        ivPointArray_headbanner = initPoint(size, headbanner_vg, ivPointArray_headbanner);

        banner_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            /**
             * 滑动后的监听
             * @param position
             */
            @Override
            public void onPageSelected(int position) {
                //修改全部的position长度
                int newPosition = position % size;

                //循环设置当前页的标记图
                for (int i = 0; i < size; i++) {
                    ivPointArray_headbanner[newPosition].setBackgroundResource(R.drawable.banner_red_radius);
                    if (newPosition != i) {
                        ivPointArray_headbanner[i].setBackgroundResource(R.drawable.banner_white_radius);
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 创建banner
     **/
    private void initBanner(HomeBanner homeBanner) {
        /**
         * 关于这里的设置参数问题,是需要这样使用的
         * 在设置了小圆点之后才能设置适配器
         * 因为只有在适配器里才会根据一共多少条数据来适配
         * 最后需要调用开始轮播
         * 个人建议在onPause()/onDestroy()方法中来停止 -- stopAutoPlay()
         */
        HomeBannerAdapter bannerAdapter = new HomeBannerAdapter(getHoldingActivity(), homeBanner);
        bannerAdapter.setSize(homeBanner.getResults().getHeader_banner().size());

        banner.setDot(R.drawable.banner_white_radius, R.drawable.banner_red_radius).
                setDotGravity(Banner.CENTER).
                setAdapter(bannerAdapter).
                setOnItemClickListener(new BannerPagerAdapter.onItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        Toast.makeText(getHoldingActivity(), position, Toast.LENGTH_SHORT).show();
                    }
                }).
                startAutoPlay();
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_a;
    }

    /**
     * 构建listview的假数据
     **/
    private static final String[] strs = new String[]{
            "first", "second", "third", "fourth", "fifth"
    };

    /**
     * 监听listview的滑动
     **/
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //获取titlebar的高度
        int height = titleBar.getHeight();
        float top = view.getChildAt(0).getY();
        L.i("@@@@@@@@@@", height + "---" + top + "firstVisibleItem" + firstVisibleItem);
    }
}
